package com.mall.service.impl;


import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.mall.constant.MessageConstant;
import com.mall.dto.ReportTop10DTO;
import com.mall.exception.BaseException;
import com.mall.mapper.OrdersMapper;
import com.mall.mapper.UserMapper;
import com.mall.po.Orders;
import com.mall.service.ReportService;
import com.mall.service.WorkSpaceService;
import com.mall.vo.*;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;


/**
 * 报表服务实现
 *
 * @author itlxc
 * @date 2024/07/01
 */
@Service
@RequiredArgsConstructor
public class ReportServiceImpl implements ReportService {

    private final OrdersMapper ordersMapper;

    private final UserMapper userMapper;

    private final WorkSpaceService workSpaceService;

    private final HttpServletResponse response;

    /**
     * 营业额统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public ReportTurnoverVO turnoverStatistics(LocalDate begin, LocalDate end) {
        // 存放begin到end范围内的日期
        List<LocalDate> dateList = getDateList(begin, end);
        // 存放每天的营业额
        List<Double> turnoverList = new ArrayList<>(dateList.size());
        dateList.forEach(date -> {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            // 统计每天营业额
            List<Orders> ordersList = Db.lambdaQuery(Orders.class)
                                        .select(Orders::getAmount)
                                        .eq(Orders::getStatus, Orders.COMPLETED)
                                        .ge(Orders::getOrderTime, beginTime)
                                        .le(Orders::getOrderTime, endTime)
                                        .list();
            BigDecimal result = ordersList.stream()
                                            .map(Orders::getAmount)
                                            .reduce(BigDecimal.valueOf(0.0), BigDecimal::add);
            turnoverList.add(result.doubleValue());
        });
        return ReportTurnoverVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .turnoverList(StringUtils.join(turnoverList, ","))
                .build();
    }

    /**
     * 获取日期列表
     * @param begin
     * @param end
     * @return
     */
    private List<LocalDate> getDateList(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!Objects.equals(begin, end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        return dateList;
    }

    /**
     * 统计用户数
     * @param begin
     * @param end
     * @return
     */
    @Override
    public ReportUsersVO userStatistics(LocalDate begin, LocalDate end) {
        // 存放begin到end范围内的日期
        List<LocalDate> dateList = getDateList(begin, end);
        // 存放每天的注册用户数
        List<Integer> newUserList = new ArrayList<>(dateList.size());
        // 存放每天的总用户数
        List<Integer> totalUserList = new ArrayList<>(dateList.size());
        dateList.forEach(date -> {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Map<String, Object> params = new HashMap<>();
            params.put("endTime", endTime);
            // 统计每天总用户数
            Integer totalUser = userMapper.countUser(params);
            params.put("beginTime", beginTime);
            // 统计每天新注册用户数
            Integer newUser = userMapper.countUser(params);
            newUserList.add(newUser);
            totalUserList.add(totalUser);
        });
        return ReportUsersVO.builder()
                            .dateList(StringUtils.join(dateList, ","))
                            .newUserList(StringUtils.join(newUserList, ","))
                            .totalUserList(StringUtils.join(totalUserList, ","))
                            .build();
    }


    /**
     * 订单统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public ReportOrdersVO ordersStatistics(LocalDate begin, LocalDate end) {
        // 存放begin到end范围内的日期
        List<LocalDate> dateList = getDateList(begin, end);
        // 存放每天总订单总数
        List<Integer> orderCountList = new ArrayList<>(dateList.size());
        // 存放每天的有效订单数
        List<Integer> validOrderCountList = new ArrayList<>(dateList.size());
        dateList.forEach(date -> {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Map<String, Object> params = new HashMap<>();
            params.put("beginTime", beginTime);
            params.put("endTime", endTime);
            // 统计每天总订单数
            Integer orderCount = ordersMapper.countOrders(params);
            params.put("status", Orders.COMPLETED);
            // 统计每天有效订单数
            Integer validOrderCount = ordersMapper.countOrders(params);
            orderCountList.add(orderCount);
            validOrderCountList.add(validOrderCount);
        });
        // 日期区间内的总订单数
        int totalOrderCount = orderCountList.stream().mapToInt(Integer::intValue).sum();
        // 日期区间内的有效订单数
        int validOrderCount = validOrderCountList.stream().mapToInt(Integer::intValue).sum();
        // 订单完成率
        double orderCompletionRate = 0.0;
        if (totalOrderCount != 0) {
            orderCompletionRate = (double) validOrderCount / totalOrderCount;
        }
        return ReportOrdersVO.builder()
                            .dateList(StringUtils.join(dateList, ","))
                            .orderCountList(StringUtils.join(orderCountList, ","))
                            .validOrderCountList(StringUtils.join(validOrderCountList, ","))
                            .totalOrderCount(totalOrderCount)
                            .validOrderCount(validOrderCount)
                            .orderCompletionRate(orderCompletionRate)
                            .build();
    }

    /**
     * 统计销量排名top10
     * @param begin
     * @param end
     * @return
     */
    @Override
    public ReportTop10VO top10(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        // 统计销量排名top10
        List<ReportTop10DTO> reportTop10DTOList = ordersMapper.countSales(beginTime, endTime, Orders.COMPLETED);
        // 存放商品名称列表
        List<String> nameList = new ArrayList<>(0);
        // 存放商品数量列表
        List<Integer> numberList = new ArrayList<>(0);
        if (CollUtil.isNotEmpty(reportTop10DTOList)) {
            nameList = reportTop10DTOList.stream().map(ReportTop10DTO::getName).toList();
            numberList = reportTop10DTOList.stream().map(ReportTop10DTO::getNumber).toList();
        }
        return ReportTop10VO.builder()
                            .nameList(StringUtils.join(nameList, ","))
                            .numberList(StringUtils.join(numberList, ","))
                            .build();
    }

    /**
     * 导出最近30天运营数据报表
     */
    @Override
    public void export() {
        // 获取最近30天日期
        LocalDate begin = LocalDate.now().minusDays(30);
        LocalDate end = LocalDate.now().minusDays(1);
        // 查询运营数据
        BusinessDataVO businessData = workSpaceService.getBusinessData(LocalDateTime.of(begin, LocalTime.MIN),
                                                        LocalDateTime.of(end, LocalTime.MAX));
        // 获取模板
        InputStream inputStream = this.getClass()
                                    .getClassLoader()
                                    .getResourceAsStream("templates/运营数据报表模板.xlsx");
        try {
            XSSFWorkbook xssfWorkbook = new XSSFWorkbook(inputStream);
            XSSFSheet sheet = xssfWorkbook.getSheet("Sheet1");
            sheet.getRow(1).getCell(1).setCellValue(begin + "至" + end);
            sheet.getRow(3).getCell(2).setCellValue(businessData.getTurnover());
            sheet.getRow(3).getCell(4).setCellValue(businessData.getOrderCompletionRate());
            sheet.getRow(3).getCell(6).setCellValue(businessData.getNewUsers());
            sheet.getRow(4).getCell(2).setCellValue(businessData.getValidOrderCount());
            sheet.getRow(4).getCell(4).setCellValue(businessData.getUnitPrice());
            // 导出近30天的运营数据
            for (int i = 0; i < 30; i++) {
                LocalDate date = begin.plusDays(i);
                BusinessDataVO data = workSpaceService.getBusinessData(LocalDateTime.of(date, LocalTime.MIN),
                                                        LocalDateTime.of(date, LocalTime.MAX));
                XSSFRow row = sheet.getRow(7 + i);
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(data.getTurnover());
                row.getCell(3).setCellValue(data.getValidOrderCount());
                row.getCell(4).setCellValue(data.getOrderCompletionRate());
                row.getCell(5).setCellValue(data.getUnitPrice());
                row.getCell(6).setCellValue(data.getNewUsers());
            }
            ServletOutputStream outputStream = response.getOutputStream();
            xssfWorkbook.write(outputStream);
            outputStream.flush();
            outputStream.close();
            xssfWorkbook.close();
        } catch (IOException e) {
            throw new BaseException(MessageConstant.ERROR_EXPORT);
        }

    }
}
